<template>
  <div class="admin-users">
    <div class="container">
      <h1 class="page-title">用户管理</h1>
      
      <div class="admin-actions">
        <el-input
          placeholder="搜索用户..."
          v-model="searchQuery"
          class="search-input"
          prefix-icon="el-icon-search"
          clearable
        />
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          @click="handleAddUser"
        >
          新增用户
        </el-button>
      </div>

      <el-card class="users-table-card" v-loading="loading">
        <el-table
          :data="filteredUsers"
          style="width: 100%"
          border
          stripe
          :default-sort="{ prop: 'created_at', order: 'descending' }"
          size="medium"
          row-class-name="table-row"
        >
          <el-table-column prop="id" label="ID" width="70" sortable />
          
          <el-table-column prop="username" label="用户名" sortable>
            <template #default="scope">
              <div class="user-info">
                <el-avatar :size="32" icon="el-icon-user"></el-avatar>
                <span>{{ scope.row.username }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="email" label="邮箱" sortable />
          
          <el-table-column prop="full_name" label="姓名" sortable />
          
          <el-table-column prop="phone" label="电话">
            <template #default="scope">
              {{ scope.row.phone || '未设置' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="is_admin" label="角色" width="100">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.is_admin">管理员</el-tag>
              <el-tag type="info" v-else>普通用户</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="注册时间" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="130">
            <template #default="scope">
              <el-dropdown trigger="hover" @command="(command) => handleCommand(command, scope.row)" placement="bottom">
                <el-button size="small" type="primary" plain class="action-button">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit" icon="el-icon-edit">编辑信息</el-dropdown-item>
                    <el-dropdown-item 
                      :command="scope.row.is_admin ? 'removeAdmin' : 'makeAdmin'" 
                      :disabled="scope.row.id === currentUser.id"
                      :icon="scope.row.is_admin ? 'el-icon-close' : 'el-icon-check'"
                      :class="{'admin-action': true, 'remove-admin': scope.row.is_admin, 'make-admin': !scope.row.is_admin}"
                    >
                      {{ scope.row.is_admin ? '取消管理员' : '设为管理员' }}
                    </el-dropdown-item>
                    <el-dropdown-item 
                      command="delete" 
                      icon="el-icon-delete" 
                      :disabled="scope.row.id === currentUser.id"
                      divided
                      class="delete-action"
                    >
                      删除用户
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalUsers"
            :page-size="10"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      :title="isAddingUser ? '新增用户' : '编辑用户信息'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="editingUser" label-width="100px" v-if="editingUser" :rules="formRules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editingUser.username" :disabled="!isAddingUser" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editingUser.email" />
        </el-form-item>
        
        <el-form-item label="姓名" prop="full_name">
          <el-input v-model="editingUser.full_name" />
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editingUser.phone" />
        </el-form-item>
        
        <el-form-item label="地址" prop="address">
          <el-input 
            type="textarea" 
            v-model="editingUser.address" 
            :rows="3" 
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="isAddingUser">
          <el-input v-model="editingUser.password" type="password" show-password />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="updating">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useStore } from 'vuex';

export default {
  name: 'AdminUsers',
  setup() {
    const store = useStore();
    const API_URL = '/api';
    const userForm = ref(null);
    
    // 状态
    const users = ref([]);
    const loading = ref(false);
    const searchQuery = ref('');
    const currentPage = ref(1);
    const dialogVisible = ref(false);
    const editingUser = ref(null);
    const updating = ref(false);
    const isAddingUser = ref(false);
    
    // 表单验证规则
    const formRules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ],
      full_name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur', validator: (rule, value, callback) => {
          if (isAddingUser.value && (!value || value.length < 6)) {
            callback(new Error('密码长度不能小于6个字符'));
          } else {
            callback();
          }
        }}
      ]
    });
    
    // 获取当前用户
    const currentUser = computed(() => store.getters['auth/currentUser']);
    
    // 获取认证头
    const authHeader = computed(() => {
      const token = store.getters['auth/token'];
      return {
        'Authorization': `Bearer ${token}`,
        'x-auth-token': token
      };
    });
    
    // 筛选后的用户
    const filteredUsers = computed(() => {
      if (!searchQuery.value) {
        return users.value;
      }
      
      const query = searchQuery.value.toLowerCase();
      return users.value.filter(user => 
        user.username.toLowerCase().includes(query) ||
        user.email.toLowerCase().includes(query) ||
        user.full_name.toLowerCase().includes(query) ||
        (user.phone && user.phone.includes(query))
      );
    });
    
    const totalUsers = computed(() => filteredUsers.value.length);
    
    // 加载所有用户
    const loadUsers = async () => {
      loading.value = true;
      try {
        const response = await axios.get(`${API_URL}/users`, { 
          headers: authHeader.value
        });
        users.value = response.data;
      } catch (error) {
        const errorMessage = error.response?.data?.message || '加载用户数据失败';
        ElMessage.error(errorMessage);
      } finally {
        loading.value = false;
      }
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      const options = { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      };
      return new Date(dateString).toLocaleDateString('zh-CN', options);
    };
    
    // 处理页面变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };
    
    // 处理下拉菜单命令
    const handleCommand = (command, user) => {
      switch(command) {
        case 'edit':
          handleEditUser(user);
          break;
        case 'makeAdmin':
          toggleAdminStatus(user, true);
          break;
        case 'removeAdmin':
          toggleAdminStatus(user, false);
          break;
        case 'delete':
          handleDeleteUser(user);
          break;
      }
    };
    
    // 编辑用户
    const handleEditUser = (user) => {
      isAddingUser.value = false;
      editingUser.value = { ...user };
      dialogVisible.value = true;
    };
    
    // 添加用户
    const handleAddUser = () => {
      isAddingUser.value = true;
      editingUser.value = {
        username: '',
        email: '',
        full_name: '',
        phone: '',
        address: '',
        password: '',
        is_admin: false
      };
      dialogVisible.value = true;
    };
    
    // 删除用户
    const handleDeleteUser = async (user) => {
      if (user.id === currentUser.value.id) {
        ElMessage.warning('不能删除自己的账户');
        return;
      }
      
      try {
        await ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复。`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await axios.delete(`${API_URL}/users/${user.id}`, {
          headers: authHeader.value
        });
        
        users.value = users.value.filter(u => u.id !== user.id);
        ElMessage.success('用户已删除');
      } catch (error) {
        if (error !== 'cancel') {
          const errorMessage = error.response?.data?.message || '删除用户失败';
          ElMessage.error(errorMessage);
        }
      }
    };
    
    // 保存用户（新增或更新）
    const saveUser = async () => {
      try {
        await userForm.value.validate();
        
        updating.value = true;
        
        if (isAddingUser.value) {
          // 新增用户
          const response = await axios.post(`${API_URL}/users`, editingUser.value, {
            headers: authHeader.value
          });
          
          users.value.push(response.data);
          ElMessage.success('用户已创建');
        } else {
          // 更新用户
          const response = await axios.put(`${API_URL}/users/${editingUser.value.id}`, {
            email: editingUser.value.email,
            full_name: editingUser.value.full_name,
            phone: editingUser.value.phone,
            address: editingUser.value.address
          }, {
            headers: authHeader.value
          });
          
          // 更新本地用户列表
          const index = users.value.findIndex(u => u.id === editingUser.value.id);
          if (index !== -1) {
            users.value[index] = response.data;
          }
          
          ElMessage.success('用户信息已更新');
        }
        
        dialogVisible.value = false;
      } catch (error) {
        if (error !== 'cancel') {
          const errorMessage = error.response?.data?.message || (isAddingUser.value ? '创建用户失败' : '更新用户信息失败');
          ElMessage.error(errorMessage);
        }
      } finally {
        updating.value = false;
      }
    };
    
    // 切换管理员状态
    const toggleAdminStatus = async (user, makeAdmin) => {
      // 防止修改自己的管理员状态
      if (user.id === currentUser.value.id) {
        ElMessage.warning('不能修改自己的管理员状态');
        return;
      }
      
      const action = makeAdmin ? '设置为' : '移除';
      const confirmMessage = `确定要${action}管理员权限吗？`;
      
      try {
        await ElMessageBox.confirm(confirmMessage, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 调用API更新用户的管理员状态
        const response = await axios.put(`${API_URL}/users/${user.id}/admin`, {
          is_admin: makeAdmin
        }, {
          headers: authHeader.value
        });
        
        // 如果服务器返回了更新后的用户对象，则使用它
        if (response.data.user) {
          const index = users.value.findIndex(u => u.id === user.id);
          if (index !== -1) {
            users.value[index] = response.data.user;
          }
        } else {
          // 否则仅更新管理员状态
          const index = users.value.findIndex(u => u.id === user.id);
          if (index !== -1) {
            users.value[index].is_admin = makeAdmin;
          }
        }
        
        ElMessage.success(`已${action}管理员权限`);
      } catch (error) {
        if (error !== 'cancel') {
          const errorMessage = error.response?.data?.message || '操作失败';
          ElMessage.error(errorMessage);
        }
      }
    };
    
    // 组件挂载时加载用户数据
    onMounted(() => {
      loadUsers();
    });
    
    return {
      users,
      filteredUsers,
      loading,
      searchQuery,
      currentPage,
      totalUsers,
      dialogVisible,
      editingUser,
      updating,
      currentUser,
      isAddingUser,
      formRules,
      userForm,
      formatDate,
      handlePageChange,
      handleEditUser,
      handleAddUser,
      handleDeleteUser,
      saveUser,
      toggleAdminStatus,
      handleCommand
    };
  }
}
</script>

<style lang="scss" scoped>
.admin-users {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
}

.admin-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  
  .search-input {
    width: 300px;
  }
}

.users-table-card {
  margin-bottom: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
      padding: 12px 0;
    }
    
    .table-row {
      transition: background-color 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

.user-info {
  display: flex;
  align-items: center;
  
  .el-avatar {
    margin-right: 10px;
    background-color: #e6f1fc;
    color: #409eff;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  display: flex;
  align-items: center;
}

.action-button {
  width: 100%;
  border-radius: 4px;
  padding: 6px 15px;
  font-size: 13px;
  transition: all 0.3s;
  
  &:hover {
    background-color: #ecf5ff;
    color: #409EFF;
    transform: translateY(-1px);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }
}

:deep(.el-dropdown-menu__item) {
  padding: 8px 20px;
  font-size: 14px;
  
  &.delete-action {
    color: #f56c6c;
    
    &:hover {
      background-color: #fef0f0;
    }
  }
  
  &.admin-action {
    &.make-admin {
      color: #67c23a;
      
      &:hover {
        background-color: #f0f9eb;
      }
    }
    
    &.remove-admin {
      color: #e6a23c;
      
      &:hover {
        background-color: #fdf6ec;
      }
    }
  }
  
  i {
    margin-right: 8px;
  }
}

:deep(.el-dropdown-menu) {
  padding: 5px 0;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 10px;
  height: 24px;
  line-height: 22px;
  
  &.el-tag--success {
    background-color: #f0f9eb;
    border-color: #e1f3d8;
  }
  
  &.el-tag--info {
    background-color: #f4f4f5;
    border-color: #e9e9eb;
  }
}
</style> 